package 常用的10种算法.prim;

import java.util.Arrays;

public class PrimAlgorithom {
    public static void main(String[] args) {
        //测试看看图是否创建成功
        char[] data = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
        int verxs = data.length;
        int[][] weight = new int[][]{
                {10000, 5, 7, 10000, 10000, 10000, 2},
                {5, 10000, 10000, 9, 10000, 10000, 3},
                {7, 10000, 10000, 10000, 8, 10000, 10000},
                {10000, 9, 10000, 10000, 10000, 4, 10000},
                {10000, 10000, 8, 10000, 10000, 5, 4},
                {10000, 10000, 10000, 4, 5, 10000, 6},
                {2, 3, 10000, 10000, 4, 6, 10000},};
        //MGraph对象
        MGraph graph = new MGraph(verxs);
        MinTree minTree = new MinTree();
        minTree.createGraph(graph, verxs, data, weight);
        minTree.show(graph);

        minTree.prim(graph, 0);
    }
}


//创建最小生成树
class MinTree {
    //创建图的邻接矩阵

    /**
     * @param graph  图对象
     * @param verxs  图对应的定点个数
     * @param data   图的各个顶点得知
     * @param weight 图的邻接矩阵
     */
    public void createGraph(MGraph graph, int verxs, char[] data, int[][] weight) {
        int i, j;
        for (i = 0; i < verxs; i++) {
            graph.data[i] = data[i];
            for (j = 0; j < verxs; j++) {
                graph.weight[i][j] = weight[i][j];
            }

        }

    }

    public void show(MGraph graph) {
        for (int[] ints : graph.weight) {
            System.out.println(Arrays.toString(ints));
        }
    }

    //编写普利姆算法
    public void prim(MGraph graph, int v) {
        int[] isvisted = new int[graph.verxs];//标记节点是否被访问过;
        //初始化为0;默认也是0
        isvisted[v] = 1;
        //记录两个顶点下表
        int h1 = -1;
        int h2 = -2;
        int minjWeight = 10000;//出事成一个较大的数,后面的遍历会对他替换

        for (int k = 1; k < graph.verxs; k++) {//有几条边,就遍历-1次
            //确定每一次生成的子图,和哪个节点的距离最近
            for (int i = 0; i < graph.verxs; i++) {//被访问过的
                for (int j = 0; j < graph.verxs; j++) {//还没有被访问过的节点
                    if (isvisted[i] == 1 && isvisted[j] == 0 && graph.weight[i][j] < minjWeight) {
                        minjWeight = graph.weight[i][j];
                        h1 = i;
                        h2 = j;
                    }
                }
            }
            System.out.println("<" + graph.data[h1] + "," + graph.data[h2] + ">" + "权值" + minjWeight);
            isvisted[h2] = 1;
            minjWeight = 1000;
        }

    }
}

class MGraph {
    int verxs;//图的节点个数
    char[] data; //存放节点数据
    int[][] weight;//存放边,邻接矩阵个

    public MGraph(int verxs) {
        this.verxs = verxs;
        data = new char[verxs];
        weight = new int[verxs][verxs];
    }

}
